<template>
    <div class="loginVideo" @keydown="handleKeyDown">
        <video src="@/assets/loginMp4.mp4" playsInline autoPlay muted cla :loop="true" :controls="false"
            preload="auto" />
        <div class="loginVideo-title animate__animated animate__backInUp">
            <img src="@/assets/logo.png" style="width: 75px;height: 75px;display: inline-block;" alt="">
            社区总览系统
        </div>
        <div class="loginBox">
            <!-- 登录框 -->
            <div class="container animate__animated animate__swing">
                <div class="drop">
                    <div class="content">
                        <h2 :style="{ color: '#3399ff' }">{{ isRegister ? '请注册' : '请登录' }}</h2>
                        <form>
                            <div v-if="isRegister" class="inputBox">
                                <div>用户名: </div>
                                <div style="flex: 0.9;" :class="{ 'animate__animated animate__bounce': isFocuse }">
                                    <input v-model="form.username" maxlength="11" type="text" placeholder="请输入用户名" />
                                </div>
                            </div>
                            <div class="inputBox">
                                <div>手机号: </div>
                                <div style="flex: 0.9;">
                                    <input v-model="form.phone" maxlength="11" type="text" placeholder="请输入手机号" />
                                </div>
                            </div>
                            <div class="inputBox">
                                <div style="width: 49px;">密码: </div>
                                <div style="flex: 0.9;" :class="{ 'animate__animated animate__bounce': isPsdFocuse }">
                                    <input v-model="form.password" type="password" maxlength="11" placeholder="请输入密码"
                                        v-on:focus="focusPassword" @blur="focusPassword" />
                                </div>
                            </div>
                            <div v-if="isRegister" class="inputBox">
                                <div style="width: 49px;">再次确认密码: </div>
                                <div style="flex: 0.9;">
                                    <input v-model="form.password2" type="password" maxlength="11"
                                        placeholder="再次输入密码" />
                                </div>
                            </div>
                            <div v-show="!isRegister" class="inputVerify" id="yanzheng">
                                <div>
                                    验证码:
                                </div>
                                <div class="inputVerify-code"
                                    :class="{ 'animate__animated animate__bounce': isCodeFocuse }">
                                    <div>
                                        <input type="text" maxlength="4" v-model="verifyCode" placeholder="验证码"
                                            v-on:focus="focusCode" @blur="focusCode" />
                                    </div>
                                    <canvas id="canvas" class="canvascs" @click="draw()">
                                    </canvas>
                                </div>
                            </div>
                            <div style="width: 275px;" v-show="!isRegister">
                                角色
                                <el-radio-group v-model="form.role" class="ml-4">
                                    <el-radio label="owner" size="large"
                                        style="color: red;font-size: 16px;font-weight: bold;">用户</el-radio>
                                    <el-radio label="admin" size="large">管理员</el-radio>
                                </el-radio-group>
                            </div>
                            <div v-if="isRegister" class="inputBox">
                                <div>邮箱: </div>
                                <div style="flex: 0.9;">
                                    <input v-model="form.email" maxlength="11" type="text" placeholder="请输入邮箱" />
                                </div>
                            </div>

                            <div class="login">
                                <el-button v-if="!isRegister" :round="true" size="large" @click="login">登录</el-button>
                                <el-button v-if="!isRegister" :round="true" size="large"
                                    @click="goRegister()">去注册</el-button>
                                <el-button v-if="isRegister" :round="true" size="large"
                                    @click="backLogin()">回到登录</el-button>
                                <el-button v-if="isRegister" :round="true" size="large" @click="login">注册</el-button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, Ref, toRaw, toValue, unref } from "vue";
import { useRouter } from "vue-router";
import { loginApi } from '@/api'
import { ElMessage } from "element-plus";
import { reqAddAccount } from "@/api/userFaimily";
export interface Form {
    phone: string,
    password: string,
    password2?: string,
    username?: string,
    email?: string,
    role: 'admin' | 'owner'
}
// form表单
let form = reactive({
    phone: '',
    username: '',
    password2: '',
    email: '',
    password: '',
    role: 'admin'
})
const isRegister = ref(false)
const router = useRouter();
const isFocuse = ref(false)
const isPsdFocuse = ref(false)
const isCodeFocuse = ref(false)
const reset = () => {
    form = reactive({
        phone: '',
        username: '',
        password2: '',
        email: '',
        password: '',
        role: 'owner'
    })
}
const focusPhone = (): void => {
    isFocuse.value = !unref(isFocuse)
}
const goRegister = () => {
    reset()
    isRegister.value = true
}
const backLogin = () => {
    isRegister.value = false
}
const focusPassword = (): void => {
    isPsdFocuse.value = !unref(isPsdFocuse)
}
const focusCode = (): void => {
    isCodeFocuse.value = !unref(isCodeFocuse)
}
const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'Enter') {
        login()
    }
}
// 登录
const login = async () => {
    console.log(toRaw(form));

    if (isRegister.value) {
        if (form.password !== form.password2) {
            return ElMessage({
                message: '两次输入密码不一致',
                type: 'warning'
            })
        }
        await reqAddAccount({ ...unref(form), role: 'owner' }).then((res: any) => {
            const { code } = res

            if (code === 200) {
                ElMessage({
                    message: '注册成功',
                    type: 'success'
                })
                reset()
                isRegister.value = false

            } else {
                const message = res.msg || '请求异常'
                ElMessage({
                    message: message,
                    type: 'warning'
                })
            }
        })
    } else {
        if (unref(verifyCode).toLowerCase() !== unref(show_num.join('')).toLowerCase()) {
            console.log("验证失败");
            draw();
            verifyCode.value = "";
            ElMessage({
                message: '图形验证码输入不正确',
                type: 'warning'
            })
            return
        }
        await loginApi(toValue(form)).then((res: any) => {
            const { code, msg } = res
            if (code === 200) {
                localStorage.setItem('isLogin', 'true')
                ElMessage({
                    message: msg,
                    type: 'success'
                })
                router.replace({
                    name: 'Home',
                    query: {
                        path: form.role === 'admin' ? 1 : 3
                    }
                })
            } else {
                ElMessage({
                    message: msg,
                    type: 'error'
                })
            }
        })
    }
}
// 绑定验证码
let verifyCode: Ref<string> = ref("");
// 验证码图形数字
var show_num: string[] = [];
onMounted(() => {
    draw();
});

//得到随机的颜色值
const randomColor = (): string => {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return `rgb(${r},${g},${b})`;
}
// 进行绘画
const draw = () => {
    //jquery对canvas对象无法获取，原生js可以解决
    var canvas_width = document.getElementById("canvas")?.clientWidth;
    var canvas_height = document.getElementById("canvas")?.clientHeight;
    var canvas = document.getElementById("canvas") as HTMLCanvasElement; //获取到canvas的对象，画布
    var context = canvas.getContext("2d")!; //画笔
    //画布范围
    canvas.width = canvas_width as number;
    canvas.height = canvas_height as number;
    //字符集
    var sCode =
        "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
    var aCode = sCode.split(",");
    var aLength = aCode.length; //获取到数组的长度
    for (var i = 0; i <= 3; i++) {
        //向下取整
        var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        var deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
        var txt = aCode[j]; //得到随机的一个字符
        show_num[i] = txt;
        var x = 10 + i * 20; //文字在canvas上的x坐标
        var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        //字体样式大小
        context.font = "23px 微软雅黑";
        //书写位置位移
        context.translate(x, y);
        //旋转
        context.rotate(deg);
        //填充的样式
        context.fillStyle = randomColor();
        //填充的字符,位置
        context.fillText(txt, 0, 0);
        //重置书写位置(上面的xy与循环中的i有关)
        context.rotate(-deg);
        context.translate(-x, -y);
    }
    //干扰项
    for (var i = 0; i <= 3; i++) {
        //验证码上显示线条
        context.strokeStyle = randomColor();
        //路线开始
        context.beginPath();
        //起点
        context.moveTo(Math.random() * (canvas_width || 0), Math.random() * (canvas_height || 0));
        //终点
        context.lineTo(Math.random() * (canvas_width || 0), Math.random() * (canvas_height || 0));
        //关闭路线
        context.closePath();
        //绘制
        context.stroke();
    }

    for (var i = 0; i <= 20; i++) {
        //验证码上显示小点
        context.strokeStyle = randomColor();
        context.beginPath();
        var x = Math.random() * (canvas_width || 0);
        var y = Math.random() * (canvas_height || 0);
        //圆心x,y,半径,起始,终点
        context.arc(x, y, 1, 0, 2 * Math.PI);
        context.closePath();
        context.stroke();
    }
    console.log("验证码：" + show_num.join(""));
    return show_num;
}
</script>

<style lang="scss" scoped>
.loginVideo {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    position: relative;

    &-title {
        left: 20px;
        position: absolute;
        top: 40px;
        font-weight: 900;
        color: rgb(51, 153, 255);
        font-size: 64px;
        font-family: '楷体';
        display: flex;
        align-items: center;
    }

    /* 验证码样式 */
    .canvascs {
        width: 92px;
        height: 30px;
        border-radius: 5px;
        margin-top: 2px;
        background: white;
        margin-left: 5px;
    }

    #yanzheng {
        display: flex;
        align-items: center;
        justify-content: space-evenly;
    }

    video {
        height: 100%;
        width: 100%;
        object-fit: cover;
        object-position: center;
    }

    .loginBox {
        position: absolute;
        top: 50%;
        right: 1%;
        transform: translate(-50%, -50%);

    }

    /* 登录框 */
    .container .drop {
        background: #e1dcdcdb;
        font-weight: 600;
        font-family: '楷体';
        position: relative;
        font-size: 20px;
        width: 440px;
        height: 440px;
        // box-shadow: inset 20px 20px 20px rgba(0, 0, 0, 0.05),
        //     25px 35px 20px rgba(0, 0, 0, 0.05), 25px 30px 30px rgba(0, 0, 0, 0.05),
        //     inset -20px -20px 25px rgba(255, 255, 255, 0.9);
        transition: 1s;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
    }

    .container .drop:hover {
        border-radius: 20%;
    }

    .container .drop::before {
        content: "";
        position: absolute;
        top: 50px;
        left: 85px;
        width: 35px;
        height: 35px;
        border-radius: 50%;
        background: #fff;
        opacity: 0.9;
    }

    .container .drop::after {
        content: "";
        position: absolute;
        top: 90px;
        left: 110px;
        width: 15px;
        height: 15px;
        border-radius: 50%;
        background: #fff;
        opacity: 0.9;
    }

    .container .drop .content {
        position: relative;
        display: flex;
        justify-content: center;
        /* align-items: center; */
        flex-direction: column;
        text-align: center;
        padding: 20px;
        gap: 15px;
    }

    .container .drop .content h2 {
        position: relative;
        color: #333;
        font-size: 1.5em;
    }

    .container .drop .content form {
        position: relative;
        display: flex;
        flex-direction: column;
        gap: 20px;
        justify-content: center;
    }

    .container .drop .content form .inputBox {
        font-size: 14px;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        font-size: 14px;
        // color: #fff;
        width: 275px;
        box-shadow: inset 2px 5px 10px rgba(0, 0, 0, 0.1),
            inset -2px -5px 10px rgba(255, 255, 255, 1),
            15px 15px 10px rgba(0, 0, 0, 0.05), 15px 10px 15px rgba(0, 0, 0, 0.025);
        border-radius: 25px;
    }

    .inputVerify {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-around;
        font-size: 14px;
        // color: #fff;
        width: 275px;
        box-shadow: inset 2px 5px 10px rgba(0, 0, 0, 0.1),
            inset -2px -5px 10px rgba(255, 255, 255, 1),
            15px 15px 10px rgba(0, 0, 0, 0.05), 15px 10px 15px rgba(0, 0, 0, 0.025);
        border-radius: 25px;
    }

    .inputVerify-code {
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: 202px;
    }

    .inputVerify input {
        border: none;
        outline: none;
        background: transparent;
        width: 78px;
        font-size: 1em;
        padding: 10px 0;
    }

    .inputVerify::before {
        content: "";
        position: absolute;
        bottom: 6px;
        left: 60px;
        width: 90px;
        height: 1px;
        background: rgb(27 26 26 / 50%);
        border-radius: 5px;
    }

    input::placeholder {
        color: rgb(4, 3, 3) !important;
        font-weight: 500 !important;
    }

    .login {
        margin: 0 auto;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-around;
        font-size: 14px;
        line-height: 20px;
        // color: #fff;
        height: 35px;
        width: 275px;
        display: flex;
        align-items: center;
        justify-content: center;
        // box-shadow: inset 2px 5px 10px rgba(0, 0, 0, 0.1),
        //     inset -2px -5px 10px rgba(255, 255, 255, 1),
        //     15px 15px 10px rgba(0, 0, 0, 0.05), 15px 10px 15px rgba(0, 0, 0, 0.025);
        border-radius: 25px;
    }

    .container .drop .content form .inputBox::before {
        content: "";
        position: absolute;
        bottom: 6px;
        left: 60px;
        width: 72%;
        height: 1px;
        background: rgb(27 26 26 / 50%);
        border-radius: 5px;
    }

    .container .drop .content form .inputBox input {
        border: none;
        outline: none;
        background: transparent;
        width: 100%;
        font-size: 1em;
        padding: 10px 0;
    }

    .container .drop .content form .login input {
        // color: white;
        text-transform: uppercase;
        font-size: 1em;
        cursor: pointer;
        background: transparent;
        border: 0;
        margin-left: 10px;
        border-radius: 10%;
        letter-spacing: 0.1em;
        font-weight: 500;
    }

    .container .drop .content form .login:last-child {
        width: 120px;
        // background: #3399ff;
        // box-shadow: inset 2px 5px 10px rgba(0, 0, 0, 0.1),
        //     15px 15px 10px rgba(0, 0, 0, 0.05), 15px 10px 15px rgba(0, 0, 0, 0.025);
        transition: 0.5s;
    }

    // .container .drop .content form .login:last-child:hover {
    //     width: 150px;
    // }

    .btns {
        position: absolute;
        right: -120px;
        bottom: 0;
        width: 120px;
        height: 120px;
        background: #00a6bc;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        text-decoration: none;
        // color: #fff;
        line-height: 1.2em;
        letter-spacing: 0.1em;
        font-size: 0.8em;
        transition: 0.25s;
        text-align: center;
        box-shadow: inset 10px 10px 10px rgba(0, 166, 188, 0.05),
            15px 25px 10px rgba(0, 166, 188, 0.1), 15px 20px 20px rgba(0, 166, 188, 0.1),
            inset -10px -10px 15px rgba(0, 166, 188, 0.5);
        border-radius: 50%;
    }

    .btns::before {
        content: "";
        position: absolute;
        top: 15px;
        left: 30px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: #fff;
        opacity: 0.45;
    }

    .btns.signup {
        bottom: 150px;
        right: -120px;
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: #00a6bc;
        box-shadow: inset 10px 10px 10px rgba(0, 166, 188, 0.05),
            15px 25px 10px rgba(0, 166, 188, 0.1), 15px 20px 20px rgba(0, 166, 188, 0.1),
            inset -10px -10px 15px rgba(0, 166, 188, 0.5);
    }

    .btns.signup::before {
        left: 20px;
        width: 15px;
        height: 15px;
    }

    .btns:hover {
        border-radius: 10%;
    }

    :deep(.el-radio__label) {
        color: #333;
        font-size: 18px;
        font-weight: 800;
    }
}
</style>